import React, { useState, useRef, useEffect } from 'react';
import { FaChevronDown, FaGithub, FaUpRightFromSquare } from 'react-icons/fa6';
import styles from './Version.module.css';

// 版本历史数据
const VERSION_HISTORY = [
  {
    version: '0.0.6',
    date: '2025-09-19',
    description: 'beta 版本',
    changes: [
      '优化对话框样式',
      '修复作品导出问题',
      '侧边栏优化'
    ]
  },
  {
    version: '0.0.5',
    date: '2025-09-18',
    description: 'beta 版本',
    changes: [
      '增加文件树显示',
      '优化UI显示效果'
    ]
  },
  {
    version: '0.0.4',
    date: '2025-09-17',
    description: 'beta 版本',
    changes: [
      '完善内部文件系统',
      '支持作品数据模型'
    ]
  },
  {
    version: '0.0.3',
    date: '2025-08-29',
    description: 'beta 版本',
    changes: [
      '增加多文件支持',
      '增加文件类型检查',
      '添加文件栏',
      '修复当前行高亮问题',
      '增加用户输入支持',
      '更新下载弹窗样式'
    ]
  },
  {
    version: '0.0.2',
    date: '2025-08-28',
    description: 'beta 版本',
    changes: [
      '添加版本信息',
      '配置持久化存储',
      '修复主题切换问题',
      '下载兼容处理'
    ]
  },
  {
    version: '0.0.1',
    date: '2025-08-27',
    description: 'beta 版本',
    changes: [
      '完整的 Python 代码编辑器',
      '实时代码执行',
      '暗色/亮色主题切换',
      '添加终端输出功能',
      '修复主题切换问题'
    ]
  },
];

const Version = () => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [dropdownPosition, setDropdownPosition] = useState({
    top: 'calc(100% + 8px)',
    left: '0',
    right: 'auto',
    maxHeight: '300px',
    width: '320px',
    direction: 'down'
  });
  const dropdownRef = useRef(null);
  const buttonRef = useRef(null);
  
  // 获取当前版本
  const currentVersion = VERSION_HISTORY[0];

  const calculateDropdownPosition = () => {
    const isMobile = window.innerWidth <= 768;
    
    if (isMobile) {
      // 移动端：真正贴住屏幕边缘
      if (!buttonRef.current) return;
      
      const buttonRect = buttonRef.current.getBoundingClientRect();
      const viewportHeight = window.innerHeight;
      const spaceBelow = viewportHeight - buttonRect.bottom - 16; // 底部边距
      const headerHeight = 60; // 大约的header高度
      const maxListHeight = spaceBelow - headerHeight - 16; // 减去header和边距
      const finalHeight = Math.max(150, Math.min(maxListHeight, 350)); // 确保不超过可用空间
      
      setDropdownPosition({
        top: 'calc(100% + 8px)',
        bottom: 'auto',
        left: `-${buttonRect.left - 16}px`, // 负边距让它贴住屏幕左边
        right: 'auto',
        maxHeight: `${finalHeight}px`,
        width: 'calc(100vw - 32px)', // 全宽度减去边距
        direction: 'down'
      });
    } else {
      // 桌面端：也需要确保不超过浏览器高度
      if (!buttonRef.current) return;
      
      const buttonRect = buttonRef.current.getBoundingClientRect();
      const viewportHeight = window.innerHeight;
      const spaceBelow = viewportHeight - buttonRect.bottom - 16;
      const headerHeight = 60;
      const maxListHeight = spaceBelow - headerHeight - 16;
      const finalHeight = Math.max(200, Math.min(maxListHeight, 300));
      
      setDropdownPosition({
        top: 'calc(100% + 8px)',
        bottom: 'auto',
        left: '0',
        right: 'auto',
        maxHeight: `${finalHeight}px`,
        width: '320px',
        direction: 'down'
      });
    }
  };

  const toggleDropdown = () => {
    if (!isDropdownOpen) {
      // 打开前计算位置
      setTimeout(() => calculateDropdownPosition(), 0);
    }
    setIsDropdownOpen(!isDropdownOpen);
  };

  const handleClickOutside = (event) => {
    if (
      dropdownRef.current && 
      !dropdownRef.current.contains(event.target) &&
      buttonRef.current && 
      !buttonRef.current.contains(event.target)
    ) {
      setIsDropdownOpen(false);
    }
  };

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 监听窗口大小变化，重新计算位置
  useEffect(() => {
    const handleResize = () => {
      if (isDropdownOpen) {
        calculateDropdownPosition();
      }
    };

    window.addEventListener('resize', handleResize);
    window.addEventListener('orientationchange', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('orientationchange', handleResize);
    };
  }, [isDropdownOpen]);

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  return (
    <div className={styles.versionContainer}>
      <button
        ref={buttonRef}
        className={styles.versionButton}
        onClick={toggleDropdown}
        title={`当前版本: v${currentVersion.version}`}
      >
        <span className={styles.versionLabel}>v{currentVersion.version}</span>
        <FaChevronDown className={`${styles.chevron} ${isDropdownOpen ? styles.chevronOpen : ''}`} />
      </button>

      {isDropdownOpen && (
        <div 
          ref={dropdownRef} 
          className={styles.dropdown}
          data-direction={dropdownPosition.direction}
          style={{
            top: dropdownPosition.top,
            bottom: dropdownPosition.bottom,
            left: dropdownPosition.left,
            right: dropdownPosition.right,
            width: dropdownPosition.width
          }}
        >
          <div className={styles.dropdownHeader}>
            <h3 className={styles.dropdownTitle}>版本历史</h3>
            <a 
              href="https://github.com/hanxiaoxin" 
              target="_blank" 
              rel="noopener noreferrer"
              className={styles.headerLink}
              onClick={(e) => {
                e.preventDefault(); // 阻止默认的链接跳转
                e.stopPropagation(); // 阻止事件冒泡
                // 确保链接能够正常跳转
                window.open('https://github.com/hanxiaoxin', '_blank', 'noopener,noreferrer');
              }}
            >
              <FaGithub className={styles.headerIcon} />
              <span className={styles.headerText}>关注作者</span>
              <FaUpRightFromSquare className={styles.headerArrow} />
            </a>
          </div>
          
          <div 
            className={styles.versionList}
            style={{ 
              maxHeight: dropdownPosition.maxHeight,
              overflowY: 'auto' // 确保可以滚动
            }}
          >
            {VERSION_HISTORY.map((version) => (
              <div 
                key={version.version} 
                className={`${styles.versionItem} ${
                  version.version === currentVersion.version ? styles.currentVersion : ''
                }`}
              >
                <div className={styles.versionHeader}>
                  <div className={styles.versionInfo}>
                    <span className={styles.versionNumber}>v{version.version}</span>
                    {version.version === currentVersion.version && (
                      <span className={styles.currentBadge}>当前</span>
                    )}
                  </div>
                  <span className={styles.versionDate}>
                    {formatDate(version.date)}
                  </span>
                </div>
                
                <p className={styles.versionDescription}>{version.description}</p>
                
                <ul className={styles.changesList}>
                  {version.changes.map((change, index) => (
                    <li key={index} className={styles.changeItem}>
                      {change}
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default Version;
